/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useState } from 'react';

type FormData = { curve?: pickedLineData; cutter: pickedVertexData[] };

type Params = {
  cutter: string[];
  curve: string;
};

function CommandCurveBreak({ title, onClose, props }: CurvedCmdDialogParams) {
  const [formData, setFormData] = useState<FormData>({ cutter: [] });

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      return;
    }
    const params: Params = props.params;
    const { curve, cutter } = params;

    await initEditDependency([...cutter, curve]);

    setFormData({
      cutter: cutter.map(
        (c) => picker.generatePickObjByPickID(c) as pickedVertexData,
      ),
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
    });
  }, []);

  const isFormDataValid = () => {
    const { curve, cutter } = formData;
    return cutter.length > 0 && curve != null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }
    const { curve, cutter } = formData;

    await confirmCommand({
      type: 'Break',
      a: { curve: curve.edgeId, cutter: cutter.map((c) => c.vertexId) },
    });

    onClose();
  };

  const { initEditDependency, initingEdit, isLoading, confirmCommand } =
    useCommand('cmd-curve-break', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateCurve',
      editDxid: props?.shape,
    });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      cutter: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickVertex,
        uniqueItems: true,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入被分割曲线',
          'ui:autofocus': true,
        },
        cutter: {
          'ui:placeholder': '请输入分割点',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      noValidate
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCurveBreak: CurvedBaseCommand = {
  id: 'CommandCurveBreak',
  label: 'command.curve-break',
  icon: 'commands/curved/curve-break',
  create: (label, onClose, props) => (
    <CommandCurveBreak
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
